<style lang="scss" scoped>
  .content {
    margin-left: 0px;
    width: 100%;
    height: 100%;
    position: relative;

  .hy-search-bar {
    position: absolute;
    top: 10px;
    width: 100%;
    background: transparent;
    border: none;
  }
  }
</style>
<template>
  <div class="content map-content">
    <div id="pathMap" class="autoHeight"></div>
    <!--搜索条部分-->
    <!--<div class="hy-search-bar">
      <div style="background-color: rgba(55,55,55,.1);height: 50px;min-width: 980px; line-height: 50px;">
        <div style="width: 980px;margin: 0 auto;">
          <div style="clear: both;height: 40px; float: left;width: 30%;">
            <i-input v-model="plateNum" readonly></i-input>
          </div>
          <div style="height: 40px;width: auto; float: left; margin-left: 30px">
            <Button type="success" shape="circle" icon="ios-search" @click="search"
                    style="margin-left: 10px;margin-top: 3px">搜索
            </Button>
          </div>
        </div>
      </div>
    </div>-->
  </div>
</template>
<script>
  import BMap from 'BMap';
  import $ from 'jQuery';
  import service from './service';
  export default {
    data () {
      return {
        plateNum: null,
        gpsno: null,
        currentVehicle: null,
        map: null,           // 地图
        marker: null,        // 标记
        searchData: {
          beginTime: '',
          endTime: ''
        },
        dongHua: [],
        label: null,
        allPoints: [], // 所有途径点
        currentPoint: 0, // 记录当前坐标点index
        startIndex: 0
      };
    },
    mounted () {
      this.searchData.beginTime = new Date(new Date().getTime() - (1000 * 60 * 60 * 5));
      this.searchData.endTime = new Date();
      this.init();
      this.gpsno = this.$route.query.gpsno;
      this.plateNum = this.$route.query.plateNum;
      if (this.plateNum && this.gpsno) {
        this.search();
      }
    },
    computed: {},
    methods: {
      // 初始化地图
      init () {
        this.map = new BMap.Map('pathMap');
        this.map.centerAndZoom(new BMap.Point(103.388611, 35.563611), 6);
        this.map.enableScrollWheelZoom(true);     // 开启鼠标滚轮缩放
      },
      // 清除地图
      clearMap () {
        this.map.clearOverlays();
      },
      getZoom (maxLng, minLng, maxLat, minLat) {
        let zoom = ['50', '100', '200', '500', '1000', '2000', '5000', '10000', '20000', '25000', '50000', '100000', '200000', '500000', '1000000', '2000000']; // 级别18到3。
        let pointA = new BMap.Point(maxLng, maxLat);  // 创建点坐标A
        let pointB = new BMap.Point(minLng, minLat);  // 创建点坐标B
        let distance = this.map.getDistance(pointA, pointB).toFixed(1);  // 获取两点距离,保留小数点后两位
        for (let i = 0, zoomLen = zoom.length; i < zoomLen; i++) {
          if (zoom[i] - distance > 0) {
            return 18 - i + 3;// 之所以会多3，是因为地图范围常常是比例尺距离的10倍以上。所以级别会增加3。
          }
        }
      },
      setZoom (points) {
        if (points.length > 0) {
          let maxLng = points[0].lng;
          let minLng = points[0].lng;
          let maxLat = points[0].lat;
          let minLat = points[0].lat;
          let res;
          for (let i = points.length - 1; i >= 0; i--) {
            res = points[i];
            if (res.lng > maxLng) maxLng = res.lng;
            if (res.lng < minLng) minLng = res.lng;
            if (res.lat > maxLat) maxLat = res.lat;
            if (res.lat < minLat) minLat = res.lat;
          }
          ;
          let cenLng = (parseFloat(maxLng) + parseFloat(minLng)) / 2;
          let cenLat = (parseFloat(maxLat) + parseFloat(minLat)) / 2;
          let zoom = this.getZoom(maxLng, minLng, maxLat, minLat);
          this.map.centerAndZoom(new BMap.Point(cenLng, cenLat), zoom);
        } else {
          // 没有坐标，显示全中国
          this.map.centerAndZoom(new BMap.Point(103.388611, 35.563611), 5);
        }
      },
      // 初始化轨迹
      initPolyline (data) {
        this.allPoints = this.getPoints(data); // 格式化坐标
        this.createPolyLine(this.allPoints); // 绘制线路
        // 添加站点、起点、终点marker
        // for (var j = 1; j < this.allPoints.length; j++) {
        //   let point = this.allPoints[j];
        //   if (j % 50 === 0) {
        //     this.addMarker('00', new BMap.Point(point.lng, point.lat));
        //   }
        // }
        this.move(); // 开始移动
        console.log(this.allPoints);
        this.setZoom(this.allPoints); // 缩放地图
      },
      createPolyLine (data) {
        // 创建线路
        var polyline = new BMap.Polyline(
          this.allPoints, // 所有的GPS坐标点
          {
            strokeColor: 'blue', // 线路颜色
            strokeWeight: 6, // 线路大小
            strokeOpacity: '0.8'
          });
        // 绘制线路
        this.map.addOverlay(polyline);
      },
      search () {
        let data = {
          plate_num: this.plateNum,
          from: this._hyTool.DateFormat(this.searchData.beginTime, 'yyyy-MM-dd hh:mm:ss'),
          to: this._hyTool.DateFormat(this.searchData.endTime, 'yyyy-MM-dd hh:mm:ss')
        };
        service.getHistoryLocation(data).then((data) => {
          this.dongHua = data.data;
          this.clearMap();
          this.currentPoint = this.dongHua.length - 1;
          this.initPolyline(this.dongHua);
        });
      },
      // 获取data数据中的经纬度点并格式化点为BMap点
      getPoints (data) {
        let points = [];
        for (let i = 0; i < data.length; i++) {
          let x = data[i].lng;
          let y = data[i].lat;
          points[i] = new BMap.Point(x, y);
        }
        return points;
      },
      // 移动
      move () {
        let carInfo = {
          no: this.plateNum
        };
        let icon = new BMap.Icon('/static/images/car.png', new BMap.Size(50, 28), {anchor: new BMap.Size(20, 12)});// 声明icon
        this.marker = new BMap.Marker(this.allPoints[this.allPoints.length - 1], {icon: icon}); // 声明标注
        this.map.addOverlay(this.marker);
        this.label = new BMap.Label(this.createLabel(this.dongHua[this.currentPoint], carInfo), {offset: new BMap.Size(-95, -170)});
        this.label.setStyle({border: '1px solid #e0dcd5', borderRadius: '5px', background: '#000', opacity: 0.8});
        this.marker.setLabel(this.label);
        $('#closeLabel').bind('click', () => {
          this.label.setStyle({display: 'none'});
        });
        let _this = this;
        // 模拟实时定位车辆
        setTimeout(function () {
          _this.resetMkPoint(_this.currentPoint);
        }, 1000);
      },
      resetMkPoint (i) {
        let carInfo = {
          no: this.plateNum
        };
        // 获取最近位置
        service.getRealLocation({gpsno: this.gpsno}).then((data) => {
          this.allPoints.push(new BMap.Point(data.data[0].lng, data.data[0].lat));
          this.dongHua.push(data.data[0]);
          this.label.setStyle({display: ''});
          this.marker.setPosition(this.allPoints[i]);// 车辆位置
          this.createPolyLine([this.allPoints[i - 1], this.allPoints[i]]);
          this.label.setContent(this.createLabel(this.dongHua[i], carInfo));
          $('#closeLabel').bind('click', () => {
            this.label.setStyle({display: 'none'});
          });
          // this.marker.setRotation(i); //车辆旋转角度
          if (i < this.allPoints.length - 1) {
            setTimeout(() => {
              i++;
              this.resetMkPoint(i);
            }, 1000);
          }
          this.currentPoint = i;
        });
      },
      createLabel (positionInfo, carInfo) {
        return this._hyTool.createMapLable(positionInfo, carInfo);
      }
    },
    watch: {
    }
  };
</script>
